package com.qfedu.common.mq.utils;

import com.qfedu.common.mq.entity.MqRetry;
import com.qfedu.common.mq.service.MqRetryService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Classname RocketMqUtils
 * @Description TODO
 * @Date 2025-09-30 9:05
 * @Created by 老任与码
 */
@Component
public class RocketMqUtils {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Resource
    private MqRetryService mqRetryService;

    /**
     * 发送同步消息
     *
     * @param topic
     * @param tag
     * @param msg
     */
    public void sendSyncMsg(String topic, String tag, String msg) {
        String destination = null;
        if (tag == null || tag.isEmpty()) {
            destination = topic;
        } else {
            destination = topic + ":" + tag;
        }
        try {
            rocketMQTemplate.syncSend(destination, msg);
        } catch (Exception e) {
            // throw new RuntimeException(e);
            // 将消息数据写入数据库的mq_retry表、
            MqRetry mqRetry = new MqRetry();
            mqRetry.setTopic(topic);
            mqRetry.setTag(tag);
            mqRetry.setMsg(msg);
            mqRetry.setUid(null);
            mqRetryService.addMqRetry(mqRetry);
        }
    }
}
